package docker

import (
	"encoding/json"
	"errors"
	"fmt"
	"os/exec"
	"runtime"
	"strings"

	"gitee.com/extrame/fb-runner/util"
	"gitee.com/extrame/fb-runner/version"
)

type DockerType byte

const (
	FabricDockers DockerType = iota + 1
	FabricDevPeers
)

//Stop the running fabric services
func Remove(t DockerType) {
	switch t {
	case FabricDockers:
		// docker rm -f $(docker ps -aq --filter label=service=hyperledger-fabric) 2>/dev/null || true
	case FabricDevPeers:
		// docker rm -f $(docker ps -aq --filter name='dev-peer*') 2>/dev/null || true
	default:
	}
}

func RemoveUnwanted(t DockerType) {
	switch t {
	case FabricDevPeers:
		// docker image rm -f $(docker images -aq --filter reference='dev-peer*') 2>/dev/null || true
	}
}

func Version() (version.Version, error) {
	// $(docker run   peer version | sed -ne 's/ Version: //p' | head -1)
	//  peer version > /dev/null 2>&1
	return ver("fabric-tools", "peer")
}

func CaVersion() (version.Version, error) {
	// $(docker run --rm hyperledger/fabric-ca:latest fabric-ca-client version | sed -ne 's/ Version: //p' | head -1)
	return ver("fabric-ca", "fabric-ca-client")
}

func Init() (err error) {
	return
}

func ver(img, cmd string) (version.Version, error) {
	cmdImages := exec.Command("docker", "images", "hyperledger/"+img, "--format", "{{json . }}")
	bts, _, err := util.Run(cmdImages, true)

	var image Image
	if err == nil {

		if bts == "" {
			err = errors.New("没有安装fabric相关docker文件，请检查安装")
			goto respondErr
		}

		var sep = "\n"
		if runtime.GOOS == "windows" {
			sep = "\r\n"
		}
		lines := strings.Split(bts, sep)
		for _, line := range lines {
			fmt.Println(line)
			err = json.Unmarshal([]byte(line), &image)
			if err == nil && image.Tag != "latest" {
				return version.Version(image.Tag), nil
			} else {
				break
			}
		}

	}
	if err == nil {
		cmdExec := exec.Command("docker", "run", "--rm", "hyperledger/"+img+":"+image.Tag, cmd, "version")
		bts, _, err = util.Run(cmdExec)
		if err == nil {
			return version.New(string(bts)), nil
		}
	}
respondErr:
	return version.New(""), err
}
